package com.ym.jiujiangeyou.bitmap;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ym.jiujiangeyou.util.FileManager;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.ImageView;

/** 
* @author 叶铭
* @Description: 图片下载  
*/
public class ImageLoader {

	private BitmapUtil bitmapUtil = null;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	// 线程池
	private ExecutorService imageThreadPool;
	private int requestSize = 120;
	private Bitmap defaultBitmap = null;
	private boolean isLoadLocalBitmapQuick = false;  //  是否直接从文件缓存取

	/**
	 * @return
	 * @retur ExecutorService
	 * @Description: 获取线层
	 */
	public ExecutorService getThreadPool() {
		if (imageThreadPool == null) {
			synchronized (ExecutorService.class) {
				if (imageThreadPool == null) {
					imageThreadPool = Executors.newFixedThreadPool(5);
				}
			}
		}
		return imageThreadPool;
	}

	public ImageLoader(Context context) {
		bitmapUtil = BitmapUtil.getInstance();
		// imageThreadPool = Executors.newFixedThreadPool(5);
	}

	public void setScaleParam(int request_size) {
		requestSize = request_size;
	}

	public void setLoadLocalBitmapQuick(boolean flag) {
		isLoadLocalBitmapQuick = flag;
	}

	/** 
	* @param drawable  
	* @retur  void 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	*/
	public void setDefaultBitmap(Drawable drawable) {
		if (drawable != null) {
			BitmapDrawable bd = (BitmapDrawable) drawable;
			defaultBitmap = bd.getBitmap();
		}
	}

	/** 
	* @param url
	* @param imageView
	* @param isLoadOnlyFromCache
	* @return  
	* @retur  boolean 
	* @Description: 图片显示 提供调用
	*/
	public boolean DisplayImage(String url, ImageView imageView,
			boolean isLoadOnlyFromCache) {
		if (url == null || url.length() < 1 || imageView == null) {
			return false;
		}

		imageViews.put(imageView, url);
		// 先从内存缓存中查找
		Bitmap bitmap = bitmapUtil.getBitmapFromLrucache(url);
		if (bitmap != null) {
			imageView.setImageBitmap(bitmap);
			return true;
		}

		// 如果true直接从缓存文件加载
		if (isLoadLocalBitmapQuick) {
			File f = FileManager.getFile(url);

			// 先从文件缓存中查找是否有
			Bitmap b = null;
			if (f != null && f.exists()) {
				b = BitmapUtil.decodeFile(f);
			}
			if (b != null) {
				imageView.setImageBitmap(b);
				return true;
			}
		}
		if (defaultBitmap != null) {

			imageView.setImageBitmap(defaultBitmap);
		}
		if (!isLoadOnlyFromCache) {
			// 若没有的话则开启新线程加载图片
			queueImage(url, imageView);
		}

		return false;

	}

	public boolean syncLoadBitmap(String url, ImageView imageView) {
		if (url == null || url.length() < 1 || imageView == null) {
			return false;
		}
		queueImage(url, imageView);
		return true;
	}

	/** 
	* @param url
	* @param imageView  
	* @retur  void 
	* @Description: 启动线程下载
	*/
	private void queueImage(String url, ImageView imageView) {
		ImageLoad il = new ImageLoad(url, imageView);
		getThreadPool().submit(new Loader(il));
	}

	private Bitmap getBitmap(String url) {
		File f = FileManager.getFile(url);

		// 先从文件缓存中查找是否有
		Bitmap b = null;
		if (f != null && f.exists()) {
			b = BitmapUtil.decodeFile(f);
		}
		if (b != null) {
			return b;
		}
		// 最后从指定的url中下载图片
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			CopyStream(is, os);
			os.close();
			bitmap = BitmapUtil.decodeFile(f);
			return bitmap;
		} catch (Exception ex) {
			Log.e("",
					ex.getMessage());
			return null;
		}
	}


	// Task for the queue
	private class ImageLoad {
		public String url;
		public ImageView imageView;

		public ImageLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	/** 
	* @author 叶铭
	* @Description: 更新UI线程 
	*/
	class Loader implements Runnable {
		ImageLoad imageLoad;

		Loader(ImageLoad imageLoad) {
			this.imageLoad = imageLoad;
		}

		@Override
		public void run() {
			if (imageViewReused(imageLoad))
				return;
			Bitmap bmp = getBitmap(imageLoad.url);
			bitmapUtil.addBitmapToLrucache(imageLoad.url, bmp);
			if (imageViewReused(imageLoad))
				return;
			BitmapDisplayer bd = new BitmapDisplayer(bmp, imageLoad);
			// 更新的操作放在UI线程中
			Activity a = (Activity) imageLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	/**
	 * 防止图片错位
	 * 
	 * @param ImageLoad
	 * @return
	 */
	boolean imageViewReused(ImageLoad ImageLoad) {
		String tag = imageViews.get(ImageLoad.imageView);
		if (tag == null || !tag.equals(ImageLoad.url))
			return true;
		return false;
	}

	
	/** 
	* @author 叶铭
	* @Description: 用于在UI线程中更新界面 
	*/
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		ImageLoad ImageLoad;

		public BitmapDisplayer(Bitmap b, ImageLoad p) {
			bitmap = b;
			ImageLoad = p;
		}

		public void run() {
			// log.e("BitmapDisplayer run...");
			if (imageViewReused(ImageLoad))
				return;
			if (bitmap != null)
				ImageLoad.imageView.setImageBitmap(bitmap);

		}
	}

	public void clearCache() {
		// memoryCache.clear();
		// fileCache.clear();
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
			Log.e("", "error...");
		}
	}
}